from fastapi import APIRouter, Depends
from pydantic import BaseModel
from apps.main import session, session_scope, db_commit
from db_models import Tbluser
from sqlalchemy.orm import Session
from apps.main import get_db
from logs.logger import slogger

router = APIRouter(prefix='/user', tags=['userTag'])


@router.get('', tags=['user'], summary='获取用户信息')
def get_user(name: str = None):
    print(name)
    data = session.query(Tbluser).all()
    # data.username = name if name else 'test'
    # db_commit(session)
    # data = session.query(Tbluser).all()
    session.close()
    return {
        'data': data
    }


class CreatUser(BaseModel):
    userid: int
    username: str

    def __str__(self):
        return "id：%s, name：%s" % (str(self.userid), self.username)


@router.post("/addUser")
async def InserUser(user: CreatUser):
    try:
        # 添加数据
        dataUser = Tbluser(userid=user.userid, username=user.username)
        session.add(dataUser)
        session.commit()
        session.close()
    except ArithmeticError:
        return {"code": "0002", "message": "数据库异常"}
    return {"code": "0000", "message": "添加成功"}

@router.post("/addUser/v2")
async def InserUser(user: CreatUser, db: Session = Depends(get_db)):
    try:
        # 添加数据
        dataUser = Tbluser(userid=user.userid, username=user.username)
        if db.query(Tbluser).filter(Tbluser.username == user.username).first():
            raise HTTPException(status_code=400, detail="用户名已存在")
        db.add(dataUser)
        db.commit()
        db.refresh(db_user)
        # session.add(dataUser)
        # session.commit()
        # session.close()
    except ArithmeticError:
        return {"code": "0002", "message": "数据库异常"}
    return {"code": "0000", "message": "添加成功"}

@router.get("", summary='查询用户列表', description="查询用户列表")
def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    users = db.query(Tbluser).offset(skip).limit(limit).all()
    return users